#!/bin/bash

echo "🔧 修复PostgreSQL连接问题"
echo "========================"

echo ""
echo "1️⃣ 停止当前容器..."
POSTGRES_CONTAINER=$(sudo docker ps | grep postgres | awk '{print $1}' | head -1)
if [ ! -z "$POSTGRES_CONTAINER" ]; then
    echo "停止容器: $POSTGRES_CONTAINER"
    sudo docker stop $POSTGRES_CONTAINER
    sudo docker rm $POSTGRES_CONTAINER
else
    echo "没有找到运行中的PostgreSQL容器"
fi

echo ""
echo "2️⃣ 清理旧数据卷..."
echo "删除旧的数据卷以确保全新初始化..."
sudo docker volume rm postgres_data 2>/dev/null || echo "数据卷不存在或已删除"

echo ""
echo "3️⃣ 创建新的PostgreSQL容器..."
echo "使用统一的密码: aide123456"
sudo docker run \
  --name postgres-aide \
  -e POSTGRES_PASSWORD=aide123456 \
  -e POSTGRES_DB=aide \
  -e POSTGRES_USER=postgres \
  -p 5432:5432 \
  -v postgres_data:/var/lib/postgresql/data \
  -d postgres:latest

echo ""
echo "4️⃣ 等待容器启动..."
sleep 10

echo ""
echo "5️⃣ 检查容器状态..."
sudo docker ps | grep postgres-aide

echo ""
echo "6️⃣ 设置正确的环境变量..."
export DATABASE_URL="postgresql://postgres:aide123456@localhost:5432/aide"
echo "DATABASE_URL已设置为: $DATABASE_URL"

echo ""
echo "7️⃣ 将环境变量写入.env文件..."
cd /home/ubuntu/aide/aide/backend
echo "DATABASE_URL=postgresql://postgres:aide123456@localhost:5432/aide" > .env
echo "JWT_SECRET=aide_jwt_secret_key_change_in_production" >> .env
echo "JWT_EXPIRES_IN=7d" >> .env
echo "PORT=5000" >> .env

echo ""
echo "8️⃣ 初始化数据库..."
echo "等待PostgreSQL完全启动..."
sleep 5

# 运行数据库初始化
node init-database-fixed.js

echo ""
echo "✅ 修复完成！"
echo ""
echo "现在可以启动后端:"
echo "  cd /home/ubuntu/aide/aide/backend"
echo "  npm run dev"
